﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WorkDAL.Voucher;
using WorkDAL;

namespace Lapas.Common.Forms
{
    public class VoucherListForm : BaseForm
    {
        public string VoucherType;
        public VcHeader CurrentVcHeader;

        private DateTime FromDate;
        private DateTime ToDate;
        private string CustomerId;
        private decimal FromAmount;
        private decimal ToAmount;
        private string UserCreate;

        public VoucherListForm()
        {
            InitializeComponent();
        }

        #region UIControls
        private System.Windows.Forms.ToolStripButton newButton;
        private System.Windows.Forms.StatusStrip mainStatusStrip;
        private ToolStripButton deleteButton;
        private System.Windows.Forms.ToolStripButton modifyButton;
        protected ToolStripStatusLabel listFormStatusLabel;
        private ToolStripButton PrintButton;
        private ToolStripButton FilterButton;
        private ToolStripButton ExitsButton;
        private Panel Headerpanel;
        private DataGridView VcHeaderGrid;
        private DataGridViewTextBoxColumn ColVoucherId;
        private DataGridViewTextBoxColumn ColVoucherType;
        private DataGridViewTextBoxColumn ColVoucherNumber;
        private DataGridViewTextBoxColumn ColVoucherDate;
        private DataGridViewTextBoxColumn ColDescription;
        private DataGridViewTextBoxColumn ColCustomerId;
        private DataGridViewTextBoxColumn ColAmount;
        private DataGridViewTextBoxColumn ColUserCreate;
        protected ToolStrip mainToolStrip;

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VoucherListForm));
            this.mainToolStrip = new System.Windows.Forms.ToolStrip();
            this.newButton = new System.Windows.Forms.ToolStripButton();
            this.modifyButton = new System.Windows.Forms.ToolStripButton();
            this.deleteButton = new System.Windows.Forms.ToolStripButton();
            this.PrintButton = new System.Windows.Forms.ToolStripButton();
            this.FilterButton = new System.Windows.Forms.ToolStripButton();
            this.ExitsButton = new System.Windows.Forms.ToolStripButton();
            this.mainStatusStrip = new System.Windows.Forms.StatusStrip();
            this.listFormStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
            this.Headerpanel = new System.Windows.Forms.Panel();
            this.VcHeaderGrid = new System.Windows.Forms.DataGridView();
            this.ColVoucherId = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColVoucherType = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColVoucherNumber = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColVoucherDate = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColDescription = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColCustomerId = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColAmount = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.ColUserCreate = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.mainToolStrip.SuspendLayout();
            this.mainStatusStrip.SuspendLayout();
            this.Headerpanel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.VcHeaderGrid)).BeginInit();
            this.SuspendLayout();
            // 
            // mainToolStrip
            // 
            this.mainToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.newButton,
            this.modifyButton,
            this.deleteButton,
            this.PrintButton,
            this.FilterButton,
            this.ExitsButton});
            this.mainToolStrip.Location = new System.Drawing.Point(0, 0);
            this.mainToolStrip.Name = "mainToolStrip";
            this.mainToolStrip.Size = new System.Drawing.Size(1154, 25);
            this.mainToolStrip.TabIndex = 0;
            this.mainToolStrip.Text = "toolStrip1";
            // 
            // newButton
            // 
            this.newButton.Image = ((System.Drawing.Image)(resources.GetObject("newButton.Image")));
            this.newButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.newButton.Name = "newButton";
            this.newButton.Size = new System.Drawing.Size(58, 22);
            this.newButton.Text = "&Thêm";
            // 
            // modifyButton
            // 
            this.modifyButton.Image = ((System.Drawing.Image)(resources.GetObject("modifyButton.Image")));
            this.modifyButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.modifyButton.Name = "modifyButton";
            this.modifyButton.Size = new System.Drawing.Size(46, 22);
            this.modifyButton.Text = "&Sửa";
            // 
            // deleteButton
            // 
            this.deleteButton.Image = global::Lapas.Common.Icons.delete1;
            this.deleteButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.deleteButton.Name = "deleteButton";
            this.deleteButton.Size = new System.Drawing.Size(47, 22);
            this.deleteButton.Text = "&Xóa";
            this.deleteButton.Click += new System.EventHandler(this.deleteButton_Click);
            // 
            // PrintButton
            // 
            this.PrintButton.Image = ((System.Drawing.Image)(resources.GetObject("PrintButton.Image")));
            this.PrintButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.PrintButton.Name = "PrintButton";
            this.PrintButton.Size = new System.Drawing.Size(37, 22);
            this.PrintButton.Text = "&In";
            // 
            // FilterButton
            // 
            this.FilterButton.Image = global::Lapas.Common.Icons.findIcon;
            this.FilterButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.FilterButton.Name = "FilterButton";
            this.FilterButton.Size = new System.Drawing.Size(46, 22);
            this.FilterButton.Text = "&Lọc";
            this.FilterButton.Click += new System.EventHandler(this.FilterButton_Click);
            // 
            // ExitsButton
            // 
            this.ExitsButton.Image = ((System.Drawing.Image)(resources.GetObject("ExitsButton.Image")));
            this.ExitsButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.ExitsButton.Name = "ExitsButton";
            this.ExitsButton.Size = new System.Drawing.Size(58, 22);
            this.ExitsButton.Text = "T&hoát";
            this.ExitsButton.Click += new System.EventHandler(this.ExitsButton_Click);
            // 
            // mainStatusStrip
            // 
            this.mainStatusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.listFormStatusLabel});
            this.mainStatusStrip.Location = new System.Drawing.Point(0, 682);
            this.mainStatusStrip.Name = "mainStatusStrip";
            this.mainStatusStrip.Size = new System.Drawing.Size(1154, 22);
            this.mainStatusStrip.TabIndex = 1;
            this.mainStatusStrip.Text = "statusStrip1";
            // 
            // listFormStatusLabel
            // 
            this.listFormStatusLabel.Name = "listFormStatusLabel";
            this.listFormStatusLabel.Size = new System.Drawing.Size(0, 17);
            // 
            // Headerpanel
            // 
            this.Headerpanel.Controls.Add(this.VcHeaderGrid);
            this.Headerpanel.Location = new System.Drawing.Point(0, 30);
            this.Headerpanel.Name = "Headerpanel";
            this.Headerpanel.Size = new System.Drawing.Size(1151, 384);
            this.Headerpanel.TabIndex = 2;
            // 
            // VcHeaderGrid
            // 
            this.VcHeaderGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.VcHeaderGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.ColVoucherId,
            this.ColVoucherType,
            this.ColVoucherNumber,
            this.ColVoucherDate,
            this.ColDescription,
            this.ColCustomerId,
            this.ColAmount,
            this.ColUserCreate});
            this.VcHeaderGrid.Dock = System.Windows.Forms.DockStyle.Fill;
            this.VcHeaderGrid.Location = new System.Drawing.Point(0, 0);
            this.VcHeaderGrid.Name = "VcHeaderGrid";
            this.VcHeaderGrid.RowTemplate.Height = 24;
            this.VcHeaderGrid.Size = new System.Drawing.Size(1151, 384);
            this.VcHeaderGrid.TabIndex = 0;
            this.VcHeaderGrid.CellEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.VcHeaderGrid_CellEnter);
            // 
            // ColVoucherId
            // 
            this.ColVoucherId.DataPropertyName = "VoucherId";
            this.ColVoucherId.HeaderText = "Id";
            this.ColVoucherId.Name = "ColVoucherId";
            this.ColVoucherId.Visible = false;
            // 
            // ColVoucherType
            // 
            this.ColVoucherType.DataPropertyName = "VoucherType";
            this.ColVoucherType.HeaderText = "CT";
            this.ColVoucherType.Name = "ColVoucherType";
            this.ColVoucherType.Width = 50;
            // 
            // ColVoucherNumber
            // 
            this.ColVoucherNumber.DataPropertyName = "VoucherDate";
            this.ColVoucherNumber.HeaderText = "Ngày CT";
            this.ColVoucherNumber.Name = "ColVoucherNumber";
            // 
            // ColVoucherDate
            // 
            this.ColVoucherDate.DataPropertyName = "VoucherNumber";
            this.ColVoucherDate.HeaderText = "Số CT";
            this.ColVoucherDate.Name = "ColVoucherDate";
            // 
            // ColDescription
            // 
            this.ColDescription.DataPropertyName = "Description";
            this.ColDescription.HeaderText = "Diễn giải";
            this.ColDescription.Name = "ColDescription";
            this.ColDescription.Width = 500;
            // 
            // ColCustomerId
            // 
            this.ColCustomerId.DataPropertyName = "CustomerId";
            this.ColCustomerId.HeaderText = "Đối tượng";
            this.ColCustomerId.Name = "ColCustomerId";
            // 
            // ColAmount
            // 
            this.ColAmount.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            this.ColAmount.DataPropertyName = "Amount";
            this.ColAmount.HeaderText = "Tổng tiền";
            this.ColAmount.Name = "ColAmount";
            this.ColAmount.Width = 150;
            // 
            // ColUserCreate
            // 
            this.ColUserCreate.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
            this.ColUserCreate.DataPropertyName = "UserCreate";
            this.ColUserCreate.HeaderText = "Người tạo";
            this.ColUserCreate.Name = "ColUserCreate";
            // 
            // VoucherListForm
            // 
            this.ClientSize = new System.Drawing.Size(1154, 704);
            this.Controls.Add(this.Headerpanel);
            this.Controls.Add(this.mainToolStrip);
            this.Controls.Add(this.mainStatusStrip);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.KeyPreview = true;
            this.MinimizeBox = false;
            this.Name = "VoucherListForm";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Resize += new System.EventHandler(this.VoucherListForm_Resize);
            this.mainToolStrip.ResumeLayout(false);
            this.mainToolStrip.PerformLayout();
            this.mainStatusStrip.ResumeLayout(false);
            this.mainStatusStrip.PerformLayout();
            this.Headerpanel.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.VcHeaderGrid)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion UIControls

        #region Private Properties

        //private DataGridView _grid = null;
        private DataGridView _voucherDetailGrid = null;
        private bool _isStockGrid = false;
        
        //DUNG CHO HEADER FILE EXCEL EXPORT
        private string _headerExcelFile;
        private string _styleExcelFile;
        private string _footerExcelFile;
        #endregion Private Properties

        #region Protected Properties

        protected virtual DataGridView Grid
        {
            get
            {
                return _voucherDetailGrid;
            }


        }

       
        protected bool IsStockGrid
        {
            get { return _isStockGrid; }
            set { _isStockGrid = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        protected ToolStripButton DeleteButton
        {
            get
            {
                return this.deleteButton;
            }

        }


        /// <summary>
        /// Hide Delete button and deactivate default delete function
        /// </summary>
        public bool HideDeleteButton
        {
            get { return !DeleteButton.Visible; }
            set { DeleteButton.Visible = !value; }
        }


        protected ToolStripButton NewButton
        {
            get
            {
                return this.newButton;
            }
        }

        protected ToolStripButton ModifyButton
        {
            get
            {
                return this.modifyButton;
            }
        }

        
        protected ToolStrip ListFormToolStrip
        {
            get
            {
                return this.mainToolStrip;
            }
        }

        protected string HeaderExcelFile
        {
            set
            {
                _headerExcelFile = value;
            }
        }

        protected string StyleExcelFile
        {
            set
            {
                _styleExcelFile = value;
            }
        }

        protected string FooterExcelFile
        {
            set
            {
                _footerExcelFile = value;
            }
        }
        #endregion Protected Properties

        #region Public Properties

        public BindingSource bindingSource = new BindingSource();
        public BindingSource vcDetailBindingSource = new BindingSource();

        private bool _bindDataOnLoad;
        /// <summary>
        /// cho phép chạy hàm bind data trong lúc load
        /// giá trị mặc định là false
        /// 20071112 TriDM
        /// </summary>
        public bool BindDataOnLoad
        {
            get { return _bindDataOnLoad; }
            set { _bindDataOnLoad = value; }
        }

        #endregion Public Properites

        #region Virtual Methodes

        protected virtual void BindData()
        {
            if (VcHeaderGrid != null)
            {
                VcHeaderGrid.DataSource = bindingSource;
                listFormStatusLabel.Text = string.Format("Tổng cộng có {0} bản ghi.", VcHeaderGrid.RowCount.ToString("n0"));
                //_voucherDetailGrid.DataSource = vcDetailBindingSource;
            }
        }

        
        
        protected virtual void LoadTotalRecords(int total)
        {
            listFormStatusLabel.Text = string.Format("Tổng cộng có {0} bản ghi.", total.ToString("n0"));
        }

        protected virtual void OnNew(object sender, EventArgs e)
        {
            DisplayEditForm(EditForm.EditFormAction.Insert);
        }

        protected virtual void OnModify(object sender, EventArgs e)
        {
            if (VcHeaderGrid == null) return;
            if (VcHeaderGrid.RowCount > 0)
                DisplayEditForm(EditForm.EditFormAction.Change);
        }

        protected virtual void OnDelete(object sender, EventArgs e)
        {

        }


        //protected virtual void OnExport(object sender, EventArgs e)
        //{
        //    if (Grid == null) return;
        //    //if Grid.DatSource==null then???
        //    //still show error when DataSource is null. review???

        //    //VanVo modify on 20070725 to export seleted rows on grid
        //    if (Grid.SelectedRows.Count == 0)
        //    {
        //        DisplayMessage.ShowNotice("Hãy chọn dữ liệu cần Export!");
        //        return;
        //    }
        //    using (SaveFileDialog saveFileDialog = new SaveFileDialog())
        //    {
        //        try
        //        {
        //            saveFileDialog.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*";
        //            saveFileDialog.FileName = this.Text;
        //            saveFileDialog.Title = "Xuất ra " + this.Text;

        //            if (saveFileDialog.ShowDialog() == DialogResult.OK && saveFileDialog.FileName.Length > 0)
        //            {
        //                DataSet dataSet = new DataSet();
        //                ObjectAdapter objectAdapter = new ObjectAdapter();
        //                DataTable dataTable = new DataTable();

        //                //Lay toan bo du lieu trong grid xuat ra Excel
        //                foreach (DataGridViewColumn column in Grid.Columns)
        //                {

        //                    dataTable.Columns.Add(column.HeaderText, typeof(string));

        //                }
        //                int rCount = 0;
        //                foreach (DataGridViewRow row in Grid.SelectedRows)
        //                {
        //                    DataRow dataRow = dataTable.NewRow();

        //                    foreach (DataGridViewColumn column in Grid.Columns)
        //                    {
        //                        // 20070927 TriDM: bo sung neu cot bi null thi tra ra string.Empty
        //                        if (row.Cells[column.Index].Value == null)
        //                        {
        //                            dataRow[column.Index] = string.Empty;
        //                        }
        //                        else
        //                        {
        //                            try
        //                            {
        //                                //Chuyen column co dinh dang Guid ve int, Guid ko co y nghia voi khach hang
        //                                Guid aa = new Guid(Convert.ToString(row.Cells[column.Index].Value));
        //                                dataRow[column.Index] = ++rCount;//row.Cells[column.Index].Value.ToString();
        //                            }
        //                            catch
        //                            {
        //                                dataRow[column.Index] = row.Cells[column.Index].Value.ToString();
        //                            }

        //                        }
        //                    }
        //                    dataTable.Rows.Add(dataRow);
        //                }

        //                //objectAdapter.Fill(dataSet, da);
        //                dataSet.Tables.Add(dataTable);
        //                ExelUtilities.ExportToExcel(dataSet, saveFileDialog.FileName, _headerExcelFile, _styleExcelFile, _footerExcelFile);
        //                DisplayMessage.ShowNotice("Export dữ liệu thành công");
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            DisplayMessage.ShowError(ex.Message);
        //        }
        //    }
        //}

        protected virtual void FormatGrid()
        {
            if (VcHeaderGrid != null)
                Lapas.Common.UIFormat.FormatGrid(VcHeaderGrid, true, true);

            if (_voucherDetailGrid != null)
                Lapas.Common.UIFormat.FormatGrid(_voucherDetailGrid, true, true);

            UIFormat.SetGridColumnFormat(ColVoucherDate, FormatType.Date);
            UIFormat.SetGridColumnFormat(ColAmount, FormatType.Number);
        }

        protected virtual void FormatBoldGrid()
        {

        }

        protected virtual void OnFilter()
        {

        }

        protected virtual void VcHeaderCellClick(Guid _VoucherId)
        {

        }

        protected virtual void DisplayEditForm(EditForm.EditFormAction action)
        { }

        protected virtual void Grid_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Delete:
                    break;
                case Keys.F2:
                    {
                        DisplayEditForm(EditForm.EditFormAction.Insert);
                        break;
                    }
                case Keys.F3:
                    {
                        DisplayEditForm(EditForm.EditFormAction.Change);
                        break;
                    }
                default:
                    break;
            }
        }

        protected virtual void Grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
          
            if (e.RowIndex >= 0)
            {
                DisplayEditForm(EditForm.EditFormAction.Change);
            }
        }

        #endregion Virtual Methodes

        #region Button Events

        private void newButton_Click(object sender, EventArgs e)
        {
            OnNew(sender, e);
        }

        private void modifyButton_Click(object sender, EventArgs e)
        {
            OnModify(sender, e);
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            if (VcHeaderGrid == null) return;
            if (VcHeaderGrid.SelectedRows.Count > 0)
            {
                if (DisplayMessage.ShowConfirm("Bạn có chắc chắn muốn xóa?"))
                {
                    CurrentVcHeader = (VcHeader)bindingSource.Current;
                    if (CurrentVcHeader != null)
                        VoucherHeaderData.Instance().Voucher_Delete(CurrentVcHeader.VoucherId);
                    OnDelete(sender, e);

                    DisplayMessage.ShowWarning("Đã xóa thành công!");
                    BindVcHeaderData(VoucherType, FromDate, ToDate, string.Empty, 0, 0, string.Empty);

                    CurrentVcHeader = (VcHeader)bindingSource.Current;
                    VcHeaderCellClick(CurrentVcHeader == null ? Guid.Empty : CurrentVcHeader.VoucherId);

                    BindData();
                }
            }
        }

        

        #endregion Button Events

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //DeleteButton.Visible = !HideDeleteButton;

            Headerpanel.Width = this.Width;
            //Detailpanel.Top = Headerpanel.Bottom + 20;

            this.Icon = base.Icon;
            if (VcHeaderGrid != null)
            {

                this.VcHeaderGrid.CellDoubleClick += new DataGridViewCellEventHandler(Grid_CellDoubleClick);
                this.VcHeaderGrid.KeyDown += new KeyEventHandler(Grid_KeyDown);
            }
            // Bind data to Grid
            SetDefaultFilter();
            FormatGrid();
            BindVcHeaderData(VoucherType, FromDate, ToDate, string.Empty, 0, 0, string.Empty);
            BindData();
            FormatBoldGrid();
        }

        private void ExitsButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FilterButton_Click(object sender, EventArgs e)
        {
            FilterForm filterForm = new FilterForm();
            filterForm.ShowDialog();

            if (!filterForm.isFilter)
                return;

            BindVcHeaderData(VoucherType, filterForm.FtFromDate, filterForm.FtToDate, filterForm.FtCustomerId, filterForm.FtFromAmount,
                                    filterForm.FtToAmount, filterForm.FtUserCreate);

            CurrentVcHeader = (VcHeader)bindingSource.Current;
            VcHeaderCellClick(CurrentVcHeader == null ? Guid.Empty : CurrentVcHeader.VoucherId);

            BindData();
            OnFilter();
        }

        private void VoucherListForm_Resize(object sender, EventArgs e)
        {
            Headerpanel.Width = this.Width;
            //Headerpanel.Height = this.Height - 20 - mainStatusStrip.Height - Detailpanel.Height;
            //Detailpanel.Top = Headerpanel.Bottom + 20;
        }

        //Bind Header Data:
        private void BindVcHeaderData(string voucherType, DateTime fromDate, DateTime toDate, string customerId, decimal fromAmount, decimal toAmount, string userCreate)
        {
            bindingSource.DataSource = VoucherHeaderData.Instance().VcHeader_GetList(voucherType, fromDate, toDate, customerId, fromAmount, toAmount, userCreate);
        }

        //Bind All Header Data:
        private void BindVcHeaderData()
        {
            bindingSource.DataSource = VoucherHeaderData.Instance().VcHeader_GetList();
        }

        private void SetDefaultFilter()
        {
            ToDate = VoucherHeaderData.Instance().Voucher_GetMaxDate(VoucherType);
            FromDate = ToDate.AddMonths(-1);
        }

        private void BindVcDetailData(Guid voucherId)
        {
            //vcDetailBindingSource.DataSource = VoucherDetail_HdData.Instance().VcDetail_HD_GetList(voucherId);
        }


        private void VcHeaderGrid_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            CurrentVcHeader = (VcHeader)bindingSource.Current;
            VcHeaderCellClick(CurrentVcHeader.VoucherId);
            
        }
    }
}
